if(!window.rtv){
	window.rtv = {};
}

if(!window.console){
	window.console = {};
	window.console.log = function(){};
}

/**
  * 初始化配置
  */
rtv.global = {
	'id_login_btn': 'wb_connect_btn',
	'id_main': 'main',
	'id_status': 'apistatus',
	'id_mainWeibo': 'main_weibo',
	'id_ulrtlist': 'rtlist',
	'id_page': 'page',
	'input_url': 'weibourl',
	'debug': false,
	'lastReqUrl': null,
	'weibo_count': 0,
	'next_max_id': 0,
	'next_since_id': 0,
	'weibo_id': 0
};


/**
  * 登录相关控制器
  */
rtv.loginCtr = {
	/**
	  * 登录成功后运行的控制器
	  */	
	'loginCallback': function(){
		window.T.dom.removeClass(rtv.global.id_main, 'hidden');
	},
	
	/**
	  * 退出成功后运行的控制器
	  */		
	'logoutCallback': function(){
		window.T.dom.addClass(rtv.global.id_main, 'hidden');
	}
};


/**
  * 获取retweet内容
  */
rtv.rtCtr = {
	'getRetweetFullStep' : function(){
		rtv.util.clearStatus();
		
		var url = window.T.dom.g(rtv.global.input_url).value;
		if('' == url || undefined == url){
			rtv.util.showError('请输入URL！');
			return false;
		}else{
			window.T.dom.g(rtv.global.id_mainWeibo).innerHTML = '';
			window.T.dom.g(rtv.global.id_ulrtlist).innerHTML = '';
			window.T.dom.g(rtv.global.id_page).innerHTML = '';
			rtv.global.lastReqUrl = url;
		}
		
		var result = this.parseInput(url);
		if(0 != result.errno){
			rtv.util.showError('URL解析失败！请使用类似于以下格式提交：(1)新浪微博主站URL，如：http://weibo.com/1711177074/xmlot5ex7；（2）新浪微博mid（即微博主站URL最后的数字字母混合）；（3）微博API纯数字ID');
			return false;			
		}
		
		if(1 == result.type){
			this.apiGetSingleWeibo(result.id);
		}else{
			this.apiQueryId(result.id);
		}
		
		return false;
	},
	
	'parseInput': function(input){
		var result = {
			'errno': 0,
			'id': 0,    //1：纯数字；2：mid
			'type': 0
		};
		
		var rstTry = input.match(/^[\d]{1,50}$/);
		if(rstTry !== null){
			result.id = rstTry[0];
			result.type = 1;
			rtv.util.showStatus('输入校验通过，按纯数字处理：' + result.id);
			return result;
		}
		
		rstTry = input.match(/^[a-zA-Z0-9]+$/);
		if(rstTry !== null){
			result.id = rstTry[0];
			result.type = 2;
			rtv.util.showStatus('输入校验通过，按mid处理：' + result.id);
			return result;
		}
		
		rstTry = input.match(/^http\:\/\/weibo\.com\/[\d]+\/([a-zA-Z0-9]+)$/);
		if(rstTry !== null){
			result.id = rstTry[1];
			result.type = 2;
			rtv.util.showStatus('输入校验通过并提取mid成功：' + result.id);
			return result;
		}
		
		result.errno = -1;
		return result;
		
	},
	
	/**
	  * 向api查询真实的API微博id：http://open.weibo.com/wiki/index.php/Queryid
	  */
	'apiQueryId': function(mid){
		rtv.util.showStatus('请求API中......（queryid.json；亲，此接口较慢，耐心等候哦）');
		window.WB2.anyWhere(function(W){
			W.parseCMD("/queryid.json", function(sResult, bStatus){
    			if(bStatus == true) {
					rtv.util.showStatus('queryid.json请求成功，得到微博id（'+ sResult.id +'）。进入下一API请求步中...');
					rtv.rtCtr.apiGetSingleWeibo(sResult.id);
    			}else{
					rtv.util.showError('向API进行mid转换查询失败，请重试。');
				}
			},{
				mid: mid,
				type: 1,
				isBase62: 1,
				is_batch: 0
			},{
    			method: 'get'
			});
		});
	},
	
	/**
	  * 向api查询某条微博的信息：http://open.weibo.com/wiki/Statuses/show
	  */
	'apiGetSingleWeibo': function(id){
		rtv.util.showStatus("请求API中......（/statuses/show/" + id +".json）");
		window.WB2.anyWhere(function(W){
			W.parseCMD("/statuses/show/" + id +".json", function(sResult, bStatus){
    			if(bStatus == true) {
					rtv.util.showStatus('statuses/show.json请求成功，进入下一步中...');
					window.T.dom.g(rtv.global.id_mainWeibo).innerHTML = rtv.tpl.mainWeibo(sResult);
					window.WB2.anyWhere(function(W){
						W.widget.load({
							'module' : 'hoverCard',
							'version' : '1.0',
							'option' : {
								'id': rtv.global.id_mainWeibo,
								search: true
							}
						});
					});
					rtv.util.showStatus('微博原内容完成渲染，进入转发列表查询中...');
					
					if(undefined !== sResult.retweeted_status){
						rtv.util.showError('错误：不是原创微博，无法查询转发内容！请输入以下数字查询该转发微博的转发信息：' + sResult.retweeted_status.id);
					}else{
						rtv.rtCtr.apiRepostTimeline(id);
					}
					return false;
    			}else{
					rtv.util.showError('向API发起/statuses/show.json查询失败，请重试。');
					return false;
				}
			},{
				id: id
			},{
    			method: 'get'
			});
		});
	},
	
	/**
	  * 向api查询某条微博的转发line：http://open.weibo.com/wiki/Statuses/repost_timeline
	  */
	'apiRepostTimeline': function(id, since_id, max_id){
		window.T.dom.g(rtv.global.id_ulrtlist).innerHTML = '';
		window.T.dom.g(rtv.global.id_page).innerHTML = '';		
		
		rtv.global.weibo_id = id;
		rtv.util.showStatus("请求API中......（/statuses/repost_timeline.json）");
		var param = {
				id: id,
				count: 30
		};
		if(max_id !== undefined){
			param.max_id = max_id;
		}
		
		if(since_id !== undefined){
			param.since_id = since_id;
		}
		
		window.WB2.anyWhere(function(W){
			W.parseCMD("/statuses/repost_timeline.json", function(sResult, bStatus){
    			if(bStatus == true) {
					rtv.util.showStatus('statuses/repost_timeline.json请求成功，进入下一步中...');
					//window._rtlist = sResult;
					rtv.global.next_max_id = 0;
					rtv.global.next_since_id = 0;
					rtv.global.weibo_count = 0;
					var finalHTML = [];
					window.T.array.each(sResult, function(item, i){
						rtv.rtCtr._logMinMax(item.id);
						finalHTML.push(rtv.tpl.rtli(item));
						rtv.global.weibo_count++;
					});
					window.T.dom.g(rtv.global.id_ulrtlist).innerHTML = finalHTML.join('');
					finalHTML = null;
					window.WB2.anyWhere(function(W){
						W.widget.load({
							'module' : 'hoverCard',
							'version' : '1.0',
							'option' : {
								'id': rtv.global.id_ulrtlist,
								search: true
							}
						});
					});
					
					window.T.dom.g(rtv.global.id_page).innerHTML = rtv.tpl.page();
					if(rtv.global.weibo_count < 1){
						rtv.util.showError('不存在转发内容，所有流程结束。');
					}else{
						rtv.util.showStatus('转发内容渲染完成，所有流程结束。');
					}
    			}else{
					rtv.util.showError('向API发起/statuses/repost_timeline.json查询失败！，请重试。');
					return false;
				}
			},
			param
			,{
    			method: 'get'
			});
		});
	},
	
	'_logMinMax': function(id){
			if(rtv.global.next_max_id < 1 || id < rtv.global.next_max_id){
				rtv.global.next_max_id = id;
			}
			if(rtv.global.next_since_id < 1 || id >= rtv.global.next_since_id){
				rtv.global.next_since_id = id;
			}
			//window.console.log(id);
	}
	
}


rtv.util = {
	
	'showStatus': function(msg){
		window.console.log(msg);
		window.T.dom.g(rtv.global.id_status).innerHTML = msg;
	},
	
	'showError': function(msg){
		window.console.log('Err Occur:' + msg);
		window.T.dom.addClass(rtv.global.id_status, 'errorMsg');		
		window.T.dom.g(rtv.global.id_status).innerHTML = msg;
	},
	
	'clearStatus': function(msg){
		window.T.dom.removeClass(rtv.global.id_status, 'errorMsg');
		window.T.dom.g(rtv.global.id_status).innerHTML = '';
	}
	
	
};


rtv.tpl = {
	'mainWeibo': function(weibo){
		if(rtv.tpl._checkIsDeleted(weibo)){
			return rtv.tpl.deleteWeibo(weibo);
		}
		
		var picHtml = '';
		if(weibo.thumbnail_pic){
			picHtml = '<p><a href="' + weibo.original_pic + '" target="_blank"><img src="' + weibo.thumbnail_pic + '" /></a></p>';
		}
		return [
			'<div id="main_userpic">',
				'<img src="' + weibo.user.profile_image_url + '" />',
			'</div>',
			' <div id="main_content">',
				'<p>', 
					'@', 
					window.T.string.filterFormat.escapeString(weibo.user.screen_name),
					'：',
					window.T.string.filterFormat.escapeString(weibo.text),
				'</p>',
				picHtml,
				'<p>',
					'<a href="http://api.t.sina.com.cn/' + weibo.user.id +'/statuses/' + weibo.id + '" target="_blank">',
					rtv.tpl.formatTime(weibo.created_at),
					'</a>&nbsp;|&nbsp;来自',
					weibo.source,
				'</p>',
			'</div>'	
		].join('');
	},
	
	'rtli': function(weibo){
		if(rtv.tpl._checkIsDeleted(weibo)){
			return '<li>' + rtv.tpl.deleteWeibo(weibo) + '</li>';
		}
		
		return [
			'<li><div class="userpic">',
				'<img src="' + weibo.user.profile_image_url + '" />',
			'</div>',
			' <div class="rtContent">',
				'<p>', 
					'@', 
					window.T.string.filterFormat.escapeString(weibo.user.screen_name),
					'：',
					window.T.string.filterFormat.escapeString(weibo.text),
				'</p>',
				'<p>',
					'<a href="http://api.t.sina.com.cn/' + weibo.user.id +'/statuses/' + weibo.id + '" target="_blank">转发于',
					rtv.tpl.formatTime(weibo.created_at),
					'</a>&nbsp;|&nbsp;来自',
					weibo.source,
				'</p>',
			'</div></li>'	
		].join('');
	},
	
	'_checkIsDeleted': function(weibo){
		return !weibo.source || weibo.deleted;
	},
	
	'deleteWeibo': function(weibo){
		return '<div>'+ window.T.string.filterFormat.escapeString(weibo.text) +'</div>';
	},
	
	'page': function(){
		var html = {
			'since': '',
			'next': ''
		};
		if(rtv.global.next_since_id > 0){
			html.since = '<span id="page_before"><a href="javascript:void(0);" onclick="rtv.rtCtr.apiRepostTimeline(\''+ rtv.global.weibo_id +'\', \''+ rtv.global.next_since_id +'\')">翻上一页</a></span>&nbsp;';
		}
		if(rtv.global.next_max_id > 0){
			html.next = '&nbsp;<span id="page_after"><a href="javascript:void(0);" onclick="rtv.rtCtr.apiRepostTimeline(\''+ rtv.global.weibo_id +'\', undefined, \''+ rtv.global.next_max_id +'\')">翻下一页</a></span>';
		}
		return html.since + html.next;
	},
	
	'formatTime': function(dateString){
		dateString = dateString.replace(/\+0800/, "UTC+0800");
		var d = new Date(dateString);
		//var d = parseISO8601(dateString);
		return d.getFullYear() + '年' + (d.getMonth() + 1) + '月' + d.getDate() + '日 ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
		//return d.toLocaleString();
	}
	
};

/**
  * 脚本初始化
  */
rtv.init = function(){
	window.WB2.anyWhere(function(W){
		W.widget.load({
			'module' : 'connectButton',
			'version' : '1.0',
			'option' : {
				id: rtv.global.id_login_btn,
				callback : {
					login: rtv.loginCtr.loginCallback,
					logout: rtv.loginCtr.logoutCallback
				}
			}
		});
	});
};